package com.qkun.library.utils;

import android.os.Bundle;
import android.os.Handler;
import android.os.ResultReceiver;

import androidx.annotation.NonNull;

import java.lang.ref.WeakReference;

public abstract class BaseResultReceiver<T> extends ResultReceiver {

    private final WeakReference<T> mCallbackRef;

    public BaseResultReceiver(Handler handler, @NonNull T callback) {
        super(handler);
        mCallbackRef = new WeakReference<>(callback);
    }

    @Override
    protected final void onReceiveResult(int resultCode, Bundle resultData) {
        super.onReceiveResult(resultCode, resultData);
        if (Utils.nonNull(mCallbackRef.get())) {
            if (Utils.nonNull(resultData)) {
                // TODO: 10/17 0017 不是每个bundle都需要setClassLoader的
                ensureClassLoader(resultData);
            }
            onReceiveResult(resultCode, resultData, mCallbackRef.get());
        } else {
            MyLog.e("Callback has been released!");
        }
    }

    protected abstract void ensureClassLoader(@NonNull Bundle bundle);

    protected abstract void onReceiveResult(int resultCode, Bundle resultData, @NonNull T callback);
}